package com.yeeverse.sdk.util;

import java.util.*;

/**
 * @Description:
 * @Author: kai.yang
 * @Date: 2020-12-30 11:46
 */
public class PropertiesUtils {

    private static final Map<String, PropertiesUtils> INSTANCE = Collections.synchronizedMap(new HashMap<>());
    private static final Object LOCK = new Object();
    private static final Map<String, String> CONVERT = Collections.synchronizedMap(new HashMap<>());
    protected String sourceUrl;
    protected ResourceBundle resourceBundle;

    protected PropertiesUtils(String sourceUrl) {
        this.sourceUrl = sourceUrl;
        load();
    }

    @SuppressWarnings("unchecked")
    public static PropertiesUtils getInstance(String sourceUrl) {
        synchronized (LOCK) {
            PropertiesUtils manager = INSTANCE.get(sourceUrl);
            if (manager == null) {
                manager = new PropertiesUtils(sourceUrl);
                INSTANCE.put(sourceUrl, manager);
            }
            return manager;
        }
    }

    private synchronized void load() {
        try {
            resourceBundle = ResourceBundle.getBundle(sourceUrl);
        } catch (Throwable e) {
            throw new RuntimeException("sourceUrl = " + sourceUrl + " file load error!", e);
        }
    }

    public synchronized String getProperty(String key) {
        return resourceBundle.getString(key);
    }

    public synchronized String getPropertyFromConvert(String key) {
        String result = CONVERT.get(key);
        if (result == null) {
            result = resourceBundle.getString(key);
            this.readyConvert();
        }
        return result;
    }

    @SuppressWarnings("rawtypes")
    public Map<String, String> readyConvert() {
        Enumeration enu = resourceBundle.getKeys();
        while (enu.hasMoreElements()) {
            String key = (String) enu.nextElement();
            String value = resourceBundle.getString(key);
            CONVERT.put(value, key);
        }
        return CONVERT;
    }

    @SuppressWarnings("rawtypes")
    public Map<String, String> readyConvert(ResourceBundle resourcebundle) {
        Enumeration enu = resourcebundle.getKeys();
        while (enu.hasMoreElements()) {
            String key = (String) enu.nextElement();
            String value = resourcebundle.getString(key);
            CONVERT.put(value, key);
        }
        return CONVERT;
    }

}
